package sg.edu.nus.comp.icreate.ivletalk.voice;

import java.util.List;

import sg.edu.nus.comp.icreate.ivletalk.BaseActivity;
import sg.edu.nus.comp.icreate.ivletalk.module.MainActivity;
import sg.edu.nus.comp.icreate.ivletalk.module.Module;
import android.content.Context;
import android.content.Intent;

public class VoiceCommandManager {
	private CommonCommandManager commonCommandManager = new CommonCommandManager();
	private List<Module> modules;
	public final static String EXTRA_VOICE_COMMAND = "voiceCommand";
	public final static String EXTRA_POSITION = "positionVoiceCommand";
	private final String MODULE_CHANGED = "--moduleChanged";
	private final double SIMILARITY_MIN = 0.5;

	public boolean executeCommand(List<String> commands, Context context) {
		if (execute(commands.get(0), context)) {
			return true;
		} else if (execute(commands.get(1), context)) {
			return true;
		}
		return false;
	}

	public boolean execute(String cmd, Context context) {
		if (commonCommandManager.chat(cmd, context)) {
			return true;
		} else if (commonCommandManager.executeMenuCommand(cmd, context)) {
			return true;
		} else if (commonCommandManager.selectItemByNumber(cmd, context)) {
			return true;
		} else if (commonCommandManager.openWebPage(cmd, context)) {
			return true;
		} else if (commonCommandManager.selectItemByName(cmd, context)) {
			return true;
		} else if (!cmd.contains(MODULE_CHANGED)) {
			if (changeModule(cmd, context))
				return true;
		}
		return false;

	}

	public boolean changeModule(String cmd, Context context) {
		modules = MainActivity.modules;
		int position = -1;
		for (Object o : modules) {
			position++;
			if (compareModuleNameAndCMD(((Module) o).toString(), cmd)) {
				return goToModule(position, context, cmd);
			}
		}
		return false;
	}

	private boolean compareModuleNameAndCMD(String name, String cmd) {
		String[] names = name.split(VoiceCommandUtil.SPACE, 2);
		if (VoiceCommandUtil.getSimilarity(VoiceCommandUtil.processString(cmd), VoiceCommandUtil.processString(names[0])) > SIMILARITY_MIN) {
			return true;
		} else if (VoiceCommandUtil.getSimilarity(VoiceCommandUtil.processString(cmd), VoiceCommandUtil.processString(names[1])) > SIMILARITY_MIN) {
			return true;
		}

		return false;
	}

	private boolean goToModule(int position, Context context, String cmd) {
		cmd = cmd + MODULE_CHANGED;
		Intent intent = new Intent(context, MainActivity.class);
		intent.putExtra(EXTRA_POSITION, position);
		intent.putExtra(EXTRA_VOICE_COMMAND, cmd);
		((BaseActivity) context).startActivity(intent);
		return true;
	}

}
